package com.uchedao.vehicledetection.loadstate.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

import com.uchedao.vehicledetection.loadstate.UCheDaoRelativeLayout;


/**
  * @ClassName: LoadstateRelativeLayout
  * @Description: 页面的等待加载
  * @author wushan
  * @date 2014-11-6 上午10:05:11
  *
  */
@SuppressLint("HandlerLeak")
public abstract class LoadstateRelativeLayout extends UCheDaoRelativeLayout implements ILoadState {

	private View mLoadingView;
	private View mLoadFailedView;
	protected View mContentView;
	private View mEmptyView;
	private boolean isInit = false;

	private Handler mHandler = new Handler() {

		@Override
		public void dispatchMessage(Message msg) {
			switch (msg.what) {
			case ILoadState.MESSAGE_ID_COMMON_LOADDATA_EMPTY:
				mLoadingView.setVisibility(View.GONE);
				mLoadFailedView.setVisibility(View.GONE);
				mContentView.setVisibility(View.GONE);
				mEmptyView.setVisibility(View.VISIBLE);
				break;
			case ILoadState.MESSAGE_ID_COMMON_LOADDATA_FAILED:
				mLoadingView.setVisibility(View.GONE);
				mLoadFailedView.setVisibility(View.VISIBLE);
				mContentView.setVisibility(View.GONE);
				mEmptyView.setVisibility(View.GONE);
				break;
			case ILoadState.MESSAGE_ID_COMMON_LOADDATA_FINISH:
				invalidateViews();
				mLoadingView.setVisibility(View.GONE);
				mLoadFailedView.setVisibility(View.GONE);
				mContentView.setVisibility(View.VISIBLE);
				mEmptyView.setVisibility(View.GONE);
				break;
			case ILoadState.MESSAGE_ID_COMMON_LOADDATA_START:
				mLoadingView.setVisibility(View.VISIBLE);
				mLoadFailedView.setVisibility(View.GONE);
				mContentView.setVisibility(View.GONE);
				mEmptyView.setVisibility(View.GONE);
				break;
			default:
				break;
			}
		};
	};

	public LoadstateRelativeLayout(Context context) {
		super(context);
		 initStateViews();
	}

	public LoadstateRelativeLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		 initStateViews();
	}

	public LoadstateRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		 initStateViews();
	}

	public void initStateViews() {
		if (isInit)
			return;
		mContentView = getContentView();
		mLoadingView = getLoadingView();
		mLoadFailedView = getLoadFailedView();
		mEmptyView = getEmptyView();
		isInit = true;
	}

	/**
	 * 刷新视图
	 */
	@Override
	public abstract void invalidateViews();

	@Override
	public void onLoadStart() {
		mHandler.sendEmptyMessage(ILoadState.MESSAGE_ID_COMMON_LOADDATA_START);
	}

	@Override
	public void onLoadFailed() {
		mHandler.sendEmptyMessage(ILoadState.MESSAGE_ID_COMMON_LOADDATA_FAILED);
	}

	@Override
	public void onLoadEmpty() {
		mHandler.sendEmptyMessage(ILoadState.MESSAGE_ID_COMMON_LOADDATA_EMPTY);
	}

	@Override
	public void onLoadSuccess() {
		mHandler.sendEmptyMessage(ILoadState.MESSAGE_ID_COMMON_LOADDATA_FINISH);
	}

}
